package com.jian.sys.controller;


import cn.hutool.core.util.IdUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.jian.sys.common.ChineseToPinYinUtils;
import com.jian.sys.common.Constant;
import com.jian.sys.common.DataGridView;
import com.jian.sys.common.ResultObj;
import com.jian.sys.pojo.Dept;
import com.jian.sys.pojo.Role;
import com.jian.sys.pojo.User;
import com.jian.sys.service.DeptService;
import com.jian.sys.service.RoleService;
import com.jian.sys.service.UserService;
import com.jian.sys.vo.UserVo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.RequestMapping;

import org.springframework.web.bind.annotation.RestController;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 剑
 * @since 2020-01-07
 */
@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    UserService userService;
    @Autowired
    DeptService deptService;
    @Autowired
    RoleService roleService;
    /**
     * 查询所有以及模糊查询
     */
    @RequestMapping("/loadAllUser")
    public DataGridView loadAllUser(UserVo userVo){

        IPage<User> page = new Page<>(userVo.getPage(),userVo.getLimit());
        QueryWrapper<User> wrapper = new QueryWrapper<>();

        wrapper.eq(StringUtils.isNotBlank(userVo.getLoginname()),"loginname",userVo.getLoginname()).or().eq(StringUtils.isNotBlank(userVo.getName()),"name",userVo.getName());
        wrapper.eq(StringUtils.isNotBlank(userVo.getAddress()),"address",userVo.getAddress());
        wrapper.eq(userVo.getDeptid()!=null,"deptid",userVo.getDeptid());
        wrapper.eq("available", Constant.USER_TYPE_NORMAL);
        this.userService.page(page,wrapper);
        List<User>list=page.getRecords();
        for (User user : list) {
            //通过部门号查找部门表返回设置所属部门名称
            if(user.getDeptid()!=null){
                Dept dept=deptService.getById(user.getDeptid());
                user.setDeptName(dept.getTitle());
            }
            //通过用户ID查找所属领导返回设置所属领导名称
            if (user.getMgr()!=null){
                User tempUser = userService.getById(user.getMgr());
                user.setLeaderName(tempUser.getName());
            }
        }
        return new DataGridView(page.getTotal(),list);
    }
    /**
     * 获取最大的排序值
     */
    @RequestMapping("/getUserMaxOrderNum")
    public Map<String,Object> getUserMaxOrderNum(){
        Map<String,Object> map = new HashMap<>();
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.orderByDesc("ordernum");
        List<User> list = this.userService.list(wrapper);
        Integer maxordernum=list.get(0).getOrdernum();
//        System.out.println(maxordernum);
        if(maxordernum!=null&&maxordernum!=1){
            map.put("value",maxordernum+1);
        }else {
            map.put("value",1);
        }
        return map;
    }

    /**
     * 通过部门ID查询该部门的所有领导
     */
    @RequestMapping("/allDeptLearName")
    public DataGridView allDeptLearName(Integer learDeptId){
        QueryWrapper<User> wrapper = new QueryWrapper<>();
        wrapper.eq(learDeptId!=null,"deptid",learDeptId);
        wrapper.eq("available",Constant.AVAILABLE_TRUE);
        wrapper.eq("type",Constant.USER_TYPE_NORMAL);
        List<User> list = this.userService.list(wrapper);
        for (User user : list) {
            System.out.println(user);
        }
        return new DataGridView(list);
    }
    /**
     * 添加用户
     */
    @RequestMapping("/addUser")
    public ResultObj addUser(UserVo userVo){
        try {
            userVo.setHiredate(new Date());
            userVo.setType(Constant.USER_TYPE_NORMAL);

            //盐
            String salt=IdUtil.simpleUUID().toUpperCase();
            userVo.setSalt(salt);
            //设置密码
            userVo.setPwd(new Md5Hash(Constant.USER_DEFAULT_PWD,salt,2).toString());
            this.userService.save(userVo);
            return ResultObj.ADD_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.ADD_ERROR;
        }
    }
    /**
     * 将用户名改为登录名--->拼音
     */
    @RequestMapping("/usernameChineseToPinYin")
    public Map<String,Object>usernameChineseToPinYin(String username){
        Map<String,Object> map = new HashMap<>();
        String pingYin = ChineseToPinYinUtils.getPingYin(username);
        map.put("value",pingYin);
        return map;
    }
    /**
     * 获取部门直属领导
     */
    @RequestMapping("/getLearDeptNameAndName")
    public DataGridView getLearDeptNameAndName(Integer learId){
        if(learId==null){
            return new DataGridView();
        }else {
            User lear = this.userService.getById(learId);
            return new DataGridView(lear);
        }
    }
    /**
     * 修改用户
     */
    @RequestMapping("/updateUser")
    public ResultObj updateUser(UserVo userVo){
        try {
            this.userService.updateById(userVo);
            return ResultObj.UPDATE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }
    /**
     * 删除用户
     */
    @RequestMapping("/deleteUser")
    public ResultObj deleteUser(Integer id){
        try {
            this.userService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }
    /**
     * 重置用户密码
     */
    @RequestMapping("/resetPwdUser")
    public ResultObj resetPwdUser(Integer id){
        try {
            User user = this.userService.getById(id);
            String salt = IdUtil.simpleUUID();
            user.setSalt(salt);
            user.setPwd(new Md5Hash(Constant.USER_DEFAULT_PWD,salt,2).toString());
            this.userService.updateById(user);
            return ResultObj.RESET_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.RESET_ERROR;
        }
    }
    /**
     * 分配用户角色的表格初始化
     */
    @RequestMapping("/userRoleTableInit")
    public DataGridView userRoleTableInit(Integer id){
        //1.查询所有可用的角色
        QueryWrapper<Role> wrapper=new QueryWrapper<>();
        wrapper.eq("available",Constant.AVAILABLE_TRUE);
        List<Map<String, Object>> listMaps = this.roleService.listMaps(wrapper);
        //2.查询用户拥有的角色
        List<Integer> userRids = this.userService.queryUserRoleByUid(id);
        if(userRids!=null){
            for (Map<String, Object> map : listMaps) {
                Boolean LAY_CHECKED=false;
                Integer roleId= (Integer) map.get("id");
                for (Integer rid : userRids) {
                    if(rid==roleId){
                        LAY_CHECKED=true;
                        break;
                    }
                }
                map.put("LAY_CHECKED",LAY_CHECKED);
            }
        }
        return new DataGridView(Long.valueOf(listMaps.size()),listMaps);
    }
    /**
     * 保存分配的角色
     */
    @RequestMapping("/saveSelectRole")
    public ResultObj saveSelectRole(Integer uid,Integer[] ids){
        try{
            this.userService.saveUserAndRole(uid,ids);
            return ResultObj.DISPATCH_SUCCESS;
        }catch (Exception e){
            e.printStackTrace();
            return ResultObj.DISPATCH_ERROR;
        }
    }
}

